from PyQt5.QtWidgets import QMenuBar, QMenu, QAction, QLabel, QPushButton, QWidget, QHBoxLayout, QFileDialog
from PyQt5.QtGui import QIcon, QPixmap, QMouseEvent, QKeySequence
from PyQt5.QtCore import QPoint, QSize
from PyQt5.Qt import Qt
import os

class MenuBar(QMenuBar):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.main_window = parent
        
        # 菜单栏拖动相关变量
        self.dragging = False
        self.drag_position = QPoint()
        
        self.setup_app_icon()
        self.setup_menus()
    
    def get_resource_path(self, relative_path):
        """获取资源文件的绝对路径，支持打包后的资源访问"""
        # 首先尝试从当前工作目录查找
        base_path = os.path.dirname(os.path.abspath(__file__))
        resource_path = os.path.join(base_path, "..", "resources", relative_path)
        
        if os.path.exists(resource_path):
            return resource_path
        
        # 如果找不到，尝试从打包后的资源目录查找
        resource_path = os.path.join("resources", relative_path)
        if os.path.exists(resource_path):
            return resource_path
        
        # 如果都找不到，返回原始路径（打包工具可能会处理）
        return os.path.join("resources", relative_path)
    
    def setup_app_icon(self):
        """设置应用程序图标和窗口控制按钮"""
        # 创建左侧图标标签
        icon_label = QLabel()
        
        # 尝试加载图标文件
        try:
            icon_path = self.get_resource_path("icons/ide.ico")
            pixmap = QPixmap(icon_path)
            if not pixmap.isNull():
                # 调整图标大小（约20x20像素）
                pixmap = pixmap.scaled(20, 20, Qt.KeepAspectRatio, Qt.SmoothTransformation)
                icon_label.setPixmap(pixmap)
            else:
                # 如果ico文件加载失败，尝试bmp文件
                bmp_path = self.get_resource_path("icons/ide.bmp")
                pixmap = QPixmap(bmp_path)
                if not pixmap.isNull():
                    pixmap = pixmap.scaled(20, 20, Qt.KeepAspectRatio, Qt.SmoothTransformation)
                    icon_label.setPixmap(pixmap)
        except Exception as e:
            print(f"加载应用程序图标失败: {e}")
        
        # 设置图标样式
        icon_label.setStyleSheet("""
            QLabel {
                background-color: transparent;
                padding: 5px;
                margin-left: 5px;
            }
            QLabel:hover {
                background-color: rgba(255, 255, 255, 0.1);
            }
        """)
        
        # 将图标添加到菜单栏最左边
        self.setCornerWidget(icon_label, Qt.TopLeftCorner)
        
        # 创建右侧窗口控制按钮
        self.setup_window_controls()
    
    def setup_window_controls(self):
        """设置窗口控制按钮（最小化、最大化/恢复、关闭）"""
        control_widget = QWidget()
        control_layout = QHBoxLayout(control_widget)
        control_layout.setContentsMargins(0, 0, 0, 0)
        control_layout.setSpacing(0)
        
        # Terminal按钮
        self.terminal_btn = QPushButton()
        self.terminal_btn.setIcon(QIcon(self.get_resource_path("icons/terminal.svg")))
        self.terminal_btn.setIconSize(QSize(16, 16))
        self.terminal_btn.setToolTip("终端")
        self.terminal_btn.clicked.connect(self.toggle_terminal_btn)
        
        # RightPanel按钮
        self.rightpanel_btn = QPushButton()
        self.rightpanel_btn.setIcon(QIcon(self.get_resource_path("icons/rightpanel.svg")))
        self.rightpanel_btn.setIconSize(QSize(16, 16))
        self.rightpanel_btn.setToolTip("右侧面板")
        self.rightpanel_btn.clicked.connect(self.toggle_right_panel_btn)
        
        # 最小化按钮
        self.min_btn = QPushButton("—")
        self.min_btn.clicked.connect(self.main_window.showMinimized)
        
        # 最大化/恢复按钮
        self.max_btn = QPushButton("□")
        self.max_btn.clicked.connect(self.toggle_maximize)
        
        # 关闭按钮
        self.close_btn = QPushButton("✕")
        self.close_btn.clicked.connect(self.main_window.close)
        
        # 设置按钮样式
        btn_style = """
            QPushButton {
                background-color: transparent;
                color: #cccccc;
                border: none;
                padding: 5px 8px;
                font-size: 14px;
            }
            QPushButton:hover {
                background-color: rgba(255, 255, 255, 0.1);
            }
            QPushButton#close_btn:hover {
                background-color: #e81123;
            }
        """
        
        # 设置图标按钮样式
        icon_btn_style = """
            QPushButton {
                background-color: transparent;
                border: none;
                padding: 5px 8px;
                color: #cccccc;
            }
            QPushButton:hover {
                background-color: rgba(255, 255, 255, 0.1);
            }
        """
        
        # 添加图标按钮
        for btn in [self.terminal_btn, self.rightpanel_btn]:
            btn.setStyleSheet(icon_btn_style)
            btn.setFixedSize(28, 28)
            control_layout.addWidget(btn)
        
        # 添加窗口控制按钮
        for btn in [self.min_btn, self.max_btn, self.close_btn]:
            btn.setStyleSheet(btn_style)
            btn.setFixedSize(30, 28)
            control_layout.addWidget(btn)
        
        # 设置关闭按钮的对象名，用于单独设置样式
        self.close_btn.setObjectName("close_btn")
        
        # 将控制按钮添加到菜单栏最右边
        self.setCornerWidget(control_widget, Qt.TopRightCorner)
        
        # 跟踪窗口状态变化，更新最大化/恢复按钮
        # 连接自定义窗口状态变化信号
        self.main_window.window_state_changed.connect(self.update_maximize_button)
    
    def toggle_maximize(self):
        """切换窗口最大化/恢复状态"""
        if self.main_window.isMaximized():
            self.main_window.showNormal()
        else:
            self.main_window.showMaximized()
    
    def update_maximize_button(self, state):
        """根据窗口状态更新最大化/恢复按钮文本"""
        if state & Qt.WindowMaximized:
            self.max_btn.setText("▢")
        else:
            self.max_btn.setText("□")
    
    def toggle_terminal_btn(self):
        """切换终端面板显示状态 - 按钮点击"""
        if hasattr(self.main_window, 'terminal'):
            current_visible = self.main_window.terminal.isVisible()
            self.toggle_terminal(not current_visible)

    def toggle_right_panel_btn(self):
        """切换右侧面板显示状态 - 按钮点击"""
        if hasattr(self.main_window, 'right_panel'):
            current_visible = self.main_window.right_panel.isVisible()
            self.toggle_right_panel(not current_visible)
    
    def setup_menus(self):
        """设置菜单栏"""
        # 文件菜单
        file_menu = self.addMenu("文件")
        
        # 新建文件操作
        new_file_action = QAction("新建文件", self)
        new_file_action.setIcon(QIcon(self.get_resource_path("icons/file.svg")))
        new_file_action.setShortcut(QKeySequence("Ctrl+N"))
        new_file_action.triggered.connect(self.new_file)
        file_menu.addAction(new_file_action)
        
        # 打开文件操作
        open_file_action = QAction("打开文件", self)
        open_file_action.setIcon(QIcon(self.get_resource_path("icons/file.svg")))
        open_file_action.setShortcut(QKeySequence("Ctrl+O"))
        open_file_action.triggered.connect(self.open_file)
        file_menu.addAction(open_file_action)
        
        # 关闭文件操作
        close_file_action = QAction("关闭文件", self)
        close_file_action.setShortcut(QKeySequence("Ctrl+W"))
        close_file_action.triggered.connect(self.close_current_file)
        file_menu.addAction(close_file_action)
        
        file_menu.addSeparator()
        
        # 打开文件夹操作
        open_folder_action = QAction("打开文件夹", self)
        open_folder_action.setIcon(QIcon(self.get_resource_path("icons/folder.svg")))
        open_folder_action.setShortcut(QKeySequence("Ctrl+Shift+O"))
        open_folder_action.triggered.connect(self.open_folder)
        file_menu.addAction(open_folder_action)
        
        # 关闭文件夹操作
        close_folder_action = QAction("关闭文件夹", self)
        close_folder_action.setShortcut(QKeySequence("Ctrl+Shift+W"))
        close_folder_action.triggered.connect(self.close_folder)
        file_menu.addAction(close_folder_action)
        
        file_menu.addSeparator()
        
        # 保存文件操作
        save_file_action = QAction("保存", self)
        save_file_action.setShortcut(QKeySequence("Ctrl+S"))
        save_file_action.triggered.connect(self.save_file)
        file_menu.addAction(save_file_action)
        
        # 另存为操作
        save_as_action = QAction("另存为", self)
        save_as_action.setShortcut(QKeySequence("Ctrl+Shift+S"))
        save_as_action.triggered.connect(self.save_as_file)
        file_menu.addAction(save_as_action)
        
        file_menu.addSeparator()
        
        # 运行文件操作
        run_file_action = QAction("运行文件", self)
        run_file_action.setIcon(QIcon(self.get_resource_path("icons/run.svg")))
        run_file_action.setShortcut(QKeySequence("F5"))
        run_file_action.triggered.connect(self.run_file)
        file_menu.addAction(run_file_action)
        
        file_menu.addSeparator()
        
        # 退出操作
        exit_action = QAction("退出", self)
        exit_action.setShortcut(QKeySequence("Alt+F4"))
        exit_action.triggered.connect(self.main_window.close)
        file_menu.addAction(exit_action)
        
        # 编辑菜单
        edit_menu = self.addMenu("编辑")
        
        # 撤销操作
        undo_action = QAction("撤销", self)
        undo_action.setShortcut(QKeySequence("Ctrl+Z"))
        edit_menu.addAction(undo_action)
        
        # 重做操作
        redo_action = QAction("重做", self)
        redo_action.setShortcut(QKeySequence("Ctrl+Y"))
        edit_menu.addAction(redo_action)
        
        edit_menu.addSeparator()
        
        # 剪切操作
        cut_action = QAction("剪切", self)
        cut_action.setShortcut(QKeySequence("Ctrl+X"))
        edit_menu.addAction(cut_action)
        
        # 复制操作
        copy_action = QAction("复制", self)
        copy_action.setShortcut(QKeySequence("Ctrl+C"))
        edit_menu.addAction(copy_action)
        
        # 粘贴操作
        paste_action = QAction("粘贴", self)
        paste_action.setShortcut(QKeySequence("Ctrl+V"))
        edit_menu.addAction(paste_action)
        
        # 视图菜单
        view_menu = self.addMenu("视图")
        
        # 终端显示/隐藏
        terminal_action = QAction("终端", self)
        terminal_action.setCheckable(True)
        terminal_action.setChecked(False)  # 默认关闭
        terminal_action.triggered.connect(self.toggle_terminal)
        view_menu.addAction(terminal_action)
        
        # 右侧面板显示/隐藏
        right_panel_action = QAction("右侧面板", self)
        right_panel_action.setCheckable(True)
        right_panel_action.setChecked(False)  # 默认关闭
        right_panel_action.triggered.connect(self.toggle_right_panel)
        view_menu.addAction(right_panel_action)
        
        view_menu.addSeparator()
        
        # 主题菜单
        theme_menu = self.addMenu("主题")
        
        # 深色主题
        dark_theme_action = QAction("深色主题", self)
        dark_theme_action.triggered.connect(self.switch_to_dark_theme)
        theme_menu.addAction(dark_theme_action)
        
        # 浅色主题
        light_theme_action = QAction("浅色主题", self)
        light_theme_action.triggered.connect(self.switch_to_light_theme)
        theme_menu.addAction(light_theme_action)
        
        # 帮助菜单
        help_menu = self.addMenu("帮助")
        
        # 关于操作
        about_action = QAction("关于", self)
        about_action.triggered.connect(self.show_about)
        help_menu.addAction(about_action)
    
    def switch_to_dark_theme(self):
        """切换到深色主题"""
        if hasattr(self.main_window, 'theme_manager'):
            stylesheet = self.main_window.theme_manager.load_theme('dark')
            if stylesheet:
                self.main_window.setStyleSheet(stylesheet)
                # 更新状态栏显示当前主题
                if hasattr(self.main_window, 'status_bar'):
                    self.main_window.status_bar.showMessage("已切换到深色主题")
    
    def switch_to_light_theme(self):
        """切换到浅色主题"""
        if hasattr(self.main_window, 'theme_manager'):
            stylesheet = self.main_window.theme_manager.load_theme('light')
            if stylesheet:
                self.main_window.setStyleSheet(stylesheet)
                # 更新状态栏显示当前主题
                if hasattr(self.main_window, 'status_bar'):
                    self.main_window.status_bar.showMessage("已切换到浅色主题")
    
    def mousePressEvent(self, event: QMouseEvent):
        """鼠标按下事件 - 开始拖动窗口"""
        # 检查是否点击在菜单项上
        action = self.actionAt(event.pos())
        if action or self.is_menu_open():
            # 如果是点击菜单项或菜单已打开，让父类处理
            return super().mousePressEvent(event)
        
        # 只有在空白区域点击时才拖动窗口
        if event.button() == Qt.LeftButton:
            self.dragging = True
            self.drag_position = event.globalPos() - self.main_window.pos()
            event.accept()
        else:
            super().mousePressEvent(event)

    def mouseMoveEvent(self, event: QMouseEvent):
        """鼠标移动事件 - 拖动窗口"""
        if self.dragging and (event.buttons() & Qt.LeftButton):
            self.main_window.move(event.globalPos() - self.drag_position)
            event.accept()
        else:
            super().mouseMoveEvent(event)

    def mouseReleaseEvent(self, event: QMouseEvent):
        """鼠标释放事件 - 停止拖动"""
        if event.button() == Qt.LeftButton:
            self.dragging = False
            event.accept()
        else:
            super().mouseReleaseEvent(event)
    
    def is_menu_open(self):
        """检查是否有菜单项处于打开状态"""
        for menu in self.findChildren(QMenu):
            if menu.isVisible():
                return True
        return False
    
    def toggle_terminal(self, checked):
        """切换终端显示状态"""
        if hasattr(self.main_window, 'terminal'):
            self.main_window.terminal.setVisible(checked)
            # 更新垂直分割器比例
            if checked:
                # 如果显示终端，设置合理比例
                self.main_window.vertical_splitter.setSizes([600, 200])
            else:
                # 如果隐藏终端，将全部空间分配给工作区
                self.main_window.vertical_splitter.setSizes([800, 0])
            
            # 更新状态栏显示
            if hasattr(self.main_window, 'status_bar'):
                status = "显示" if checked else "隐藏"
                self.main_window.status_bar.showMessage(f"已{status}终端")
    
    def toggle_right_panel(self, checked):
        """切换右侧面板显示状态"""
        if hasattr(self.main_window, 'right_panel'):
            self.main_window.right_panel.setVisible(checked)
            
            # 获取当前尺寸
            current_sizes = self.main_window.main_splitter.sizes()
            
            if checked:
                # 如果显示右侧面板，分配300px空间
                new_sizes = [
                    current_sizes[0],  # 侧边栏
                    current_sizes[1],  # 资源管理器
                    current_sizes[2] - 300,  # 工作区/终端
                    300  # 右侧面板
                ]
            else:
                # 如果隐藏右侧面板，将空间分配给工作区
                panel_width = current_sizes[3]
                new_sizes = [
                    current_sizes[0],  # 侧边栏
                    current_sizes[1],  # 资源管理器
                    current_sizes[2] + panel_width,  # 工作区/终端
                    0  # 右侧面板
                ]
            
            # 应用新尺寸
            self.main_window.main_splitter.setSizes(new_sizes)
            
            # 更新状态栏显示
            if hasattr(self.main_window, 'status_bar'):
                status = "显示" if checked else "隐藏"
                self.main_window.status_bar.showMessage(f"已{status}右侧面板")
    
    def get_stylesheet(self):
        # 由于样式现在由主题系统统一管理，这里返回空字符串
        return ""
    
    def new_file(self):
        """新建文件"""
        if hasattr(self.main_window, 'workspace'):
            editor = self.main_window.workspace.add_tab("Untitled")
            if hasattr(self.main_window, 'status_bar'):
                self.main_window.status_bar.showMessage("已创建新文件")
    
    def open_file(self):
        """打开文件"""
        file_path, _ = QFileDialog.getOpenFileName(
            self.main_window, 
            "选择文件", 
            "", 
            "文本文件 (*.txt *.py *.js *.html *.css *.json *.xml *.md);;所有文件 (*.*)"
        )
        
        if file_path and os.path.isfile(file_path):
            # 检查文件是否已经在工作区打开
            if hasattr(self.main_window, 'workspace'):
                if self.main_window.workspace.open_file(file_path):
                    if hasattr(self.main_window, 'status_bar'):
                        self.main_window.status_bar.showMessage(f"已打开文件: {os.path.basename(file_path)}")
    
    def close_current_file(self):
        """关闭当前文件"""
        if hasattr(self.main_window, 'workspace'):
            if self.main_window.workspace.close_current_tab():
                if hasattr(self.main_window, 'status_bar'):
                    self.main_window.status_bar.showMessage("已关闭当前文件")
    
    def open_folder(self):
        """打开文件夹"""
        folder_path = QFileDialog.getExistingDirectory(
            self.main_window, 
            "选择文件夹", 
            ""
        )
        
        if folder_path and os.path.isdir(folder_path):
            # 在资源管理器中显示文件夹
            if hasattr(self.main_window, 'file_explorer'):
                self.main_window.file_explorer.load_folder(folder_path)
                if hasattr(self.main_window, 'status_bar'):
                    self.main_window.status_bar.showMessage(f"已打开文件夹: {os.path.basename(folder_path)}")
    
    def close_folder(self):
        """关闭文件夹"""
        if hasattr(self.main_window, 'file_explorer'):
            self.main_window.file_explorer.clear()
            if hasattr(self.main_window, 'status_bar'):
                    self.main_window.status_bar.showMessage("已关闭文件夹")
    
    def save_file(self):
        """保存文件"""
        if hasattr(self.main_window, 'workspace'):
            if self.main_window.workspace.save_current_file():
                if hasattr(self.main_window, 'status_bar'):
                    self.main_window.status_bar.showMessage("文件已保存")
    
    def save_as_file(self):
        """另存为文件"""
        if hasattr(self.main_window, 'workspace'):
            if self.main_window.workspace.save_as_current_file():
                if hasattr(self.main_window, 'status_bar'):
                    self.main_window.status_bar.showMessage("文件已另存为")
    
    def run_file(self):
        """运行当前文件"""
        if hasattr(self.main_window, 'run_manager'):
            self.main_window.run_manager.run_current_file()
    
    def show_about(self):
        """显示关于对话框"""
        from PyQt5.QtWidgets import QMessageBox
        
        about_text = """<span style='color: gray;'>CodeIdea IDE

        一个轻量级的代码编辑器
        支持多种编程语言和文件类型

        版本: 0.1.0
        开发者: BaiLejing</span>"""
        
        msg_box = QMessageBox(self.main_window)
        msg_box.setWindowTitle("关于 CodeIdea")
        msg_box.setText(about_text)
        msg_box.setStyleSheet("QLabel{color: gray;}")
        msg_box.exec_()